<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NInput,
  NTag,
  useMessage,
  NFlex,
  NAvatar, NSelect, NInputNumber, NFormItem, NForm
} from 'naive-ui'

import api from '@/api'
import TheIcon from "@/components/icon/TheIcon.vue";
import {getToken, isExternal} from "@/utils";
import {useCRUD} from "@/composables";
import default_image from "@/assets/images/mz.jpg";
import AppPage from "@/components/page/AppPage.vue";
const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
const message = useMessage()



const {
  modalVisible,
  modalTitle,
  modalLoading,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
  handleSave,
} = useCRUD({
  name: '组合包',
  initForm: {},
  doCreate: api.creategoodsGroup,
  doUpdate: api.updategoodsGroup,
  doDelete: api.deletegoodsGroup,
  refresh: () => $table.value?.handlerefresh(),
})

const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);

function save_all() {
  data.include = {
    bd_include: data.groups1,
    zx_include: data.groups2,
    zx_can_do: data.can_do,
  }
  props.modelValue.include = data.include
  props.modelValue.showGoodsModal = false

}

const data = reactive({
  add_group: false,
  goods: [],
  goods_tree: [],
  category_id: 0,
  groups1: [],
  groups2: [],
  select_skus: [],
  type2: 1,
  sku_id: 0,
  goods_id: 0,
  can_do: 1,
  type: 2,
  times: 1,
  group_name: "",
  include: {
    bd_include: [],
    zx_include: [],
    zx_can_do: 0
  }
})

function add_group() {
  data.goods = []
  data.select_skus = []
  get_goods_tree()
  data.add_group = true
}

function select_tab(value) {

  if (value === "必得组合") {
    data.type2 = 1
  } else {
    data.type2 = 2
  }

  return true
}

function get_goods() {
  api.getgoodsGood({
    category_id: data.category_id,
    type: "1,2",
    page_size: 100
  }).then((res) => (data.goods = res.data))
}

function get_goods_tree() {
  api.getgoodsCategoryTree().then((res) => (data.goods_tree = res.data))
}

function delete_group(id) {
  api.deletegoodsGroup({data_id: id}).then((res) => (get_groups()))
}

onMounted(() => {
  data.sku_id = props.modelValue.sku_id
  data.goods_id = props.modelValue.goods_id
  data.can_do = props.modelValue.can_do
  get_groups()
})

function handleMenuSelect(key, item) {
  data.category_id = key
  get_goods()
}

function get_groups() {
  api.getgoodsGroup({
    sku_id: data.sku_id,
    type2: 1
  }).then((res) => (data.groups1 = res.data))

  api.getgoodsGroup({
    sku_id: data.sku_id,
    type2: 2
  }).then((res) => (data.groups2 = res.data))
}

function save_group() {
  if (!data.group_name) {
    message.error('请输入组合包名称')
    return
  }
  // if(data.select_skus.length===0){
  //   message.error('请先选择购买商品数量')
  //   return
  // }
  api.creategoodsGroup({
    name: data.group_name,
    sku_id: data.sku_id,
    goods_id: data.goods_id,
    type: data.type,
    times: data.times,
    goods: data.select_skus,
    type2: data.type2
  }).then((res) => {
    message.success(res.msg)
    get_groups()
    data.add_group = false
  })
}


function handleChange(value, index1, index2) {
  console.log(value, index1, index2)
  // data.select_skus = []//选中的商品规则和数量
  data.select_price = 0
  data.goods[index1].sku[index2].select_nums = value;
  data.goods.map(item => {
    item.sku.map(item_sku => {
      if (item_sku.select_nums > 0) {
        data.select_price += item_sku.select_nums * item_sku.sku_level[1]
        const skuIndex = data.select_skus.findIndex(item => item.sku_id === item_sku.id)

        if (skuIndex !== -1) {
          data.select_skus[skuIndex].num = item_sku.select_nums;
        } else {
          data.select_skus.push(
              {
                "sku_id": item_sku.id,
                "sku_name": item_sku.sku_name,
                "num": item_sku.select_nums,
                "goods_name": item.name,
              }
          )
        }
      }
    })
  });

}


</script>

<template>
  <AppPage :show-footer="false">
    <div
        id="drawer-target"
    >
      <n-card :bordered="false" :segmented="{ content: true, footer: 'soft'}">
        <template #header>
          <n-h6 prefix="bar" style="margin: 0;font-size: 18px">商品组合包{{ props.modelValue.sku_id }}</n-h6>
        </template>

        <n-tabs type="segment" animated size="large" :tabs-padding="0" pane-style="padding: 20px;"
                @before-leave="select_tab">
          <n-tab-pane name="必得组合" style="min-height: 300px">
            <n-flex>
              <n-card v-for="item in data.groups1" :title="item.name+'-'+item.id" size="small" hoverable embedded
                      style="width: auto" closable @close="delete_group(item.id)"
                      :segmented="{ content: true, footer: 'soft'}">
                <n-flex style="margin-bottom: 5px" v-for="item2 in item.goods">
                  <n-tag type="primary">{{ item2.goods_name }}-{{ item2.sku_name }}</n-tag>
                  <n-tag type="error" v-if="item.type===1">{{ item2.num }}次</n-tag>
                </n-flex>
                <template #footer>
                  <n-alert type="warning" v-if="item.type===1">单独次数计算</n-alert>
                  <n-alert type="warning" v-if="item.type===2">项目合计{{ item.times }}次</n-alert>
                  <n-alert type="warning" v-if="item.type===3">过期时间{{ item.times }}日</n-alert>
                </template>
              </n-card>
              <n-card @click="add_group" size="small" hoverable embedded
                      style="width: auto;background: #d7d4d9;cursor: pointer"
                      :segmented="{ content: true, footer: 'soft'}">
                <div style="justify-content: center;align-items: center;height: 100%;width: 100px;display: flex">
                  <TheIcon icon="material-symbols:add" :size="38"/>
                </div>
              </n-card>
            </n-flex>
            <n-flex style="margin-top: 15px">
              <n-tag type="error" size="large">以上为开卡直接获得得组合,可以为空</n-tag>
            </n-flex>
          </n-tab-pane>

        </n-tabs>

        <template #footer>
          <n-alert title="组合包说明:" type="error">
            总次：例如顾客开卡时选择获得组合01，组合内共有3个项目，总次的可选次数为1，则代表顾客可以在这个组合内3选1进行消费<br>
            分次：例如顾客开卡时选择获得组合02，组合类型为分次，则代表顾客可以消费组合内的每一个项目<br>
            自选：收银/开卡时可在所有可选的组合中，任选其中之一组合或者任选多个组合<br>
            必得：收银/开卡时卡内一定包含这个组合
          </n-alert>
          <n-button type="primary" @click="save_all" class="mt-15">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5"/>
            保存
          </n-button>

        </template>
      </n-card>

      <n-drawer v-model:show="data.add_group" width="80%" show-mask='transparent' :trap-focus="false"
                :block-scroll="false" to="#drawer-target" style="border-radius: 10px">
        <n-drawer-content title="添加新的组合包" closable>

          <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="100" :model="modalForm"
                 size="large" :rules="validate">
            <NFlex>
              <NFormItem label="组合包名称" path="group_name">
                <n-input v-model:value="data.group_name" clearable placeholder="组合包名称"/>
              </NFormItem>
              <NFormItem label="组合包类型" path="type">
                <n-radio-group name="radiogroup" :default-value="2" v-model:value="data.type">
                  <n-space>
                    <n-radio key=1 :value=1>分次</n-radio>
                    <n-radio key=2 :value=2>总次</n-radio>
                    <n-radio key=3 :value=3>时段</n-radio>
                  </n-space>
                </n-radio-group>
              </NFormItem>
              <NFormItem label="总可用次数" path="times" v-if="data.type===2">
                <n-input-number v-model:value="data.times" clearable placeholder="请输入次数" min="1"/>
              </NFormItem>
              <NFormItem label="总时长(天)" path="times" v-if="data.type===3">
                <n-input-number v-model:value="data.times" clearable placeholder="总时长(天)" min="1"/>
              </NFormItem>
            </NFlex>


            <n-card :bordered="false" embedded :segmented="{ content: true, footer: 'soft'}" size="small">
              <template #header>
                <n-h6 prefix="bar" style="margin: 0;font-size: 14px">商品选择</n-h6>
              </template>
              <template #header-extra>
                <n-button type="primary" @click="save_group()" size="small">保存</n-button>
              </template>
              <n-flex>
                <div style="background: #fff;border-radius: 10px;width: 160px;border:1px solid #eee">
                  <n-scrollbar style="max-height: calc(100vh - 300px);padding:0">
                    <n-menu
                        :options="data.goods_tree"
                        :root-indent="16"
                        :indent="10"
                        @update:value="handleMenuSelect"
                    />
                  </n-scrollbar>
                </div>
                <div style="flex: 1">
                  <n-scrollbar v-if="data.goods.length>0" style="max-height: calc(100vh - 300px);padding:0">
                    <n-card v-for="(item,index1) in data.goods" class="customer_card" hover:card-shadow size="small"
                            :segmented="{
                    content: true,
                    footer: 'soft',
                  }">
                      <template #header-extra>
                        <NTag style="width: 80px" size="large">库存:{{ item.kc }}</NTag>
                      </template>
                      <template #header>
                        <div style="display: flex; align-items: center;">
                          <NAvatar :src="item.cover" :fallbackSrc="default_image"
                                   style="width: 30px; height: 30px; margin-right: 10px;"/>
                          <span>{{ item.name }}</span>
                        </div>
                      </template>

                      <n-flex v-for="(sku_item,index2) in item.sku" justify="space-between" size="large"
                              style="width:100%;height:30px;line-height:30px;margin-bottom:2px">
                        <div>规格: <span>{{ sku_item.sku_name }}(¥{{ sku_item.sku_level[1] }})</span></div>
                        <div>
                          <n-input-number button-placement="both" size="tiny" :min="0" style="width: 80px"
                                          v-model:value=sku_item.select_nums
                                          @update:value="(value) => handleChange(value, index1, index2)"/>
                        </div>
                      </n-flex>
                    </n-card>
                  </n-scrollbar>
                  <div v-else
                       style="height: calc(100vh - 300px);display: flex;align-items: center;justify-content: center">
                    <n-empty size="large" description="请选择分类"></n-empty>
                  </div>
                </div>
              </n-flex>
            </n-card>

          </NForm>
        </n-drawer-content>
      </n-drawer>
    </div>
  </AppPage>
</template>


<style>
.customer_card {
  margin: 0 10px 10px 10px;
  width: 95%;
}
</style>